package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.PageResult;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.model.sys.User;
import com.weipai.springboot.module.dao.AdminDao;
import com.weipai.springboot.module.dao.ArtisanDao;
import com.weipai.springboot.module.dao.CustomerDao;
import com.weipai.springboot.module.dao.SystemDao;
import com.weipai.springboot.module.mapper.AdminMapper;
import com.weipai.springboot.module.service.AdminService;
import com.weipai.springboot.module.util.DateUtils;
import com.weipai.springboot.util.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/13 09:57
 * <p>
 * 管理员
 */
@Service
public class AdminServiceImpl implements AdminService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    AdminDao adminDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    ArtisanDao artisanDao;

    //管理员的新增
    @Override
    public Response save(Admin admin) {
        Response response = new Response();
        admin.setAdminPassword(PasswordHelper.encryptPassword(admin.getAdminPassword(), admin.getAdminLoginName()));
        admin.setAdminCode(String.valueOf(createAdminCode()));
        Admin oldAdmin = adminDao.getAdminByLoginName(admin.getAdminLoginName());
        if(null == oldAdmin){
            if (1 == adminDao.insert(admin)) {
                response.setCode(RetCode.SUCCESS);
            } else {
                logger.debug("保存管理员失败:{}", admin.getAdminLoginName());
                response.setCode(RetCode.SAVE_ERROR);
            }
        }else{
            response.setCode(RetCode.REPEAT_DATA);
        }
        return response;
    }

    /**
     * 生成六位推荐码
     * @return
     */
    private int createAdminCode(){
        int adminCode = (int)((Math.random()*9+1)*100000);
        if(adminDao.verifyCustomerByInviCode(String.valueOf(adminCode))>0){
            createAdminCode();
        }
        return adminCode;
    }

    //分页查询
    @Override
    public List<Map<String, Object>> selectAllByDel(int del, String search, String sort, String way) {
        return adminDao.selectAllByDel(del, search, sort, way);
    }

    //查询管理员详情
    @Override
    public Response getAdminById(String id) {
        Response response = new Response();
        Admin admin = adminDao.getAdminById(id);
        if (null != admin) {
            response.setCode(RetCode.SUCCESS);
            response.put("obj", admin);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //管理员的修改
    @Override
    public Response update(Admin admin) {
        Response response = new Response();
        admin.setUpdateTime(DateUtils.timeFormat(System.currentTimeMillis()));
        if (1 == adminDao.updateByPrimaryKey22(admin)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            logger.debug("修改管理员信息失败:{}", admin.getAdminLoginName());
            response.setCode(RetCode.SAVE_ERROR);
        }
        return response;
    }

    //删除
    @Override
    public Response deleteById(String id) {
        Response response = new Response();
        if (1 == adminDao.updateDel(id)) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.DEL_ERROR);
        }
        return response;
    }

    //批量删除
    @Override
    public Response batchDeleteById(String[] id) {
        Response response = new Response();
        if (adminDao.batchDeleteById(id) > 0) {
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.DEL_ERROR);
        }
        return response;
    }

    @Override
    public Response getCustomerCategoryList() {
        Response response = new Response();
        List<CustomerCategory> categories = adminDao.getCustomerCategoryList();
        if (categories.size() > 0) {
            response.setCode(RetCode.SUCCESS);
            response.setData(categories);
        } else {
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //更改会员的类别
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response changeCustomerCategory(String customerId, String customerCategoryId, String type) {
        Response response = new Response();
        Customer customer = customerDao.getCustomerById(customerId);
        // 从普通会员 到员工 或大客户
        if(1==customer.getCustomerCategoryId() && (type.equals("2") || type.equals("4"))) {

            //判断此用户是否注册过技工,
            Artisan artisan2  =artisanDao.getArtisanByCustomerId(customerId);
            if (artisan2!=null){
                response.setCode(RetCode.ARTISAN_TOCUSTOMER);
                return response;
            }

            //从普通客户到员工
            if(type.equals("4")){
                Admin admin1 = adminDao.getAdminByCustomerId(customerId);
                if(null==admin1){
                    Admin admin = new Admin();
                    admin.setAdminCode(String.valueOf(createAdminCode()));  //形成推荐码
                    admin.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                    admin.setAdminLoginName(customer.getCustomerLoginName());
                    admin.setAdminMobile(customer.getCustomerMobile());
                    admin.setCustomerId(customerId);
                    admin.setAdminPassword(customer.getCustomerPassword());
                    adminDao.insert(admin);
                    customer.setAdminCode(admin.getAdminCode());
                }else {
                    admin1.setAdminDel(0); //大客户变为员工  重新启动员工信息
                    admin1.setAdminCode(String.valueOf(createAdminCode()));  //11.9 改 形成新的推荐码   之前 从大客户变为员工,推荐码为空,后台 员工列表无法显示
                    adminDao.updateByPrimaryKey22(admin1);
                    customer.setAdminCode(admin1.getAdminCode());
                }
            }
        }

        // 从大客户 转 普通会员 或者 员工
        if(2==customer.getCustomerCategoryId() && (type.equals("1") || type.equals("4"))){
            if(customer.getUseReputation()<customer.getCustomerReputation()){
                response.setCode(RetCode.RETURN_REPUTATION);
                return response;
            }
            customer.setCustomerReputation(0);
            customer.setUseReputation(0);
            if(type.equals("4")){
                Admin admin1 = adminDao.getAdminByCustomerId(customerId);
                if(null==admin1){
                    Admin admin = new Admin();
                    admin.setAdminCode(String.valueOf(createAdminCode()));  //形成推荐码
                    admin.setCreateTime(DateUtils.timeFormat(System.currentTimeMillis()));
                    admin.setAdminLoginName(customer.getCustomerLoginName());
                    admin.setAdminMobile(customer.getCustomerMobile());
                    admin.setCustomerId(customerId);
                    admin.setAdminPassword(customer.getCustomerPassword());
                    adminDao.insert(admin);
                    customer.setAdminCode(admin.getAdminCode());
                }else {
                    admin1.setAdminDel(0); //大客户变为员工  重新启动员工信息
                    admin1.setAdminCode(String.valueOf(createAdminCode()));  //11.9 改 形成新的推荐码   之前 从大客户变为员工,推荐码为空,后台 员工列表无法显示
                    adminDao.updateByPrimaryKey22(admin1);
                    customer.setAdminCode(admin1.getAdminCode());
                }
            }
        }
        //从 员工  -------------到 普通会员  或  大客户
        if(4==customer.getCustomerCategoryId() && (type.equals("1") || type.equals("2"))){
            Admin admin = adminDao.getAdminByCustomerId(customerId);
            admin.setAdminCode("");   //推荐码  为空
            admin.setAdminDel(-1);
            adminDao.updateByPrimaryKey22(admin);
            customer.setAdminCode("");
        }
        customer.setCustomerCategoryId(Integer.parseInt(customerCategoryId));
        customerDao.updateByPrimaryKey(customer);
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    //记录管理员登录日志
    @Override
    public Response saveAdminLoginRecord(AdminLoginRecord adminLoginRecord) {
        Response response = new Response();
        if(1==adminDao.saveAdminLoginRecord(adminLoginRecord)){
            response.setCode(RetCode.SUCCESS);
        }else{
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //管理员登录记录
    @Override
    public Response getAdminLoginRecordList(Integer page, Integer size, String startTime, String endTime, String draw, String adminLoginName) {
        Response response = new Response();
        Integer start = (page-1) * size;
        List<Map<String, Object>> adminLoginRecordList = adminDao.getAdminLoginRecordList(adminLoginName, start, size, startTime, endTime);
        Integer amount = adminDao.getAdminLoginRecordAmount(adminLoginName, startTime, endTime);
        if(amount>=1){
            PageResult<Map<String, Object>> pageList = new PageResult<>(adminLoginRecordList,page,size,amount, draw);
            response.setCode(RetCode.SUCCESS);
            response.put("pageList", pageList);
        }else{
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }
}
